package com.niu.wm.web.controller;


import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.niu.wm.core.ResponseObject;
import com.niu.wm.model.User;
import com.niu.wm.service.UserService;

@Controller
public class HomeController extends BaseController{
	
	@Autowired
	private UserService userService;
	@Autowired
	private AuthenticationManager authenticationManager;
	
	@RequestMapping(value = "signin")
	public String signin(HttpServletRequest request, ModelMap model) {
		Exception e = (Exception) request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
		if(e != null){
			model.addAttribute("message", "用户名或密码错误" );
		}	
        return "signin/signin";
    }
	
	@RequestMapping({"/","/workshop"})
    public String workshop(HttpServletRequest request, ModelMap model){
		User user = this.getCurrentUser();
		model.addAttribute("user", user);
		
		return "workshop";
	}
	
	
	@RequestMapping(value = "/navigatorTree.do")
    public String navigator(HttpServletRequest request, ModelMap model){
		User user = this.getCurrentUser();
		model.addAttribute("user", user);
		
		
		return "navigatorTree";
	}
	
	@RequestMapping(value = "/top.do")
    public String top(HttpServletRequest request, ModelMap model){
		User user = this.getCurrentUser();
		model.addAttribute("user", user);
		
		return "top";
	}
	
	@RequestMapping(value = "layout/north")
	public String north(HttpServletRequest request, ModelMap model) {
		User user = this.getCurrentUser();
		model.put("user", user);
        return "layout/north";
    }
	
	@RequestMapping(value="/test/test.do") 
	@ResponseBody
	public ResponseObject<String> test(){
		User u = userService.loadByAccount("system");
		if(u == null)
			logger.debug("user is not exists");
		else
			logger.debug("user is exists");
		
		return new ResponseObject<>("Hello");
	}
	
	@RequestMapping(value="/login") 
	@ResponseBody
	public LoginInfo login(@RequestParam(defaultValue="") String username,@RequestParam(defaultValue="") String password,HttpServletRequest request){
		String fromIP = request.getRemoteAddr();
		username = username.trim();
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
		try {
			Authentication authentication = authenticationManager.authenticate(authRequest); //调用loadUserByUsername
			SecurityContextHolder.getContext().setAuthentication(authentication);
			HttpSession session = request.getSession();
			session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext()); // 这个非常重要，否则验证后将无法登陆
			
			User user = this.getCurrentUser();
			//登录日志
			userService.loginLog(user, fromIP);
			
			return new LoginInfo().success().setMsg(authentication.getName());
		} catch (AuthenticationException ex) {
			return new LoginInfo().failed().setMsg("用户名或密码错误");
		}
	}
	
	public static class LoginInfo{
		private Boolean successFlag;
		private String msg;
		
		public Boolean getSuccessFlag(){
			return successFlag;
		}
		
		public LoginInfo success(){
			this.successFlag = true;
			return this;
		}
		
		public LoginInfo failed(){
			this.successFlag = false;
			return this;
		}

		public String getMsg() {
			return msg;
		}

		public LoginInfo setMsg(String msg) {
			this.msg = msg;
			return this;
		}
	}
}
